//package GraWLiczby;
import java.io.*;
import java.net.*;

public class ServerThread extends Thread {
	private Socket socket1;
	private Socket socket2;
	private GameData game;

	public ServerThread(Socket socket1,Socket socket2) {
		this.socket1 = socket1;
		this.socket2 = socket2;
		this.game = new GameData();
	}
	
	public void run() {
		try {
			System.out.println("New Thread");
			BufferedReader in1 = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
			PrintWriter out1 = new PrintWriter(socket1.getOutputStream(), true);
			BufferedReader in2 = new BufferedReader(new InputStreamReader(socket2.getInputStream()));
			PrintWriter out2 = new PrintWriter(socket2.getOutputStream(), true);
			

			out1.println("hello you the first one");
			out2.println("hello you're the second one");
			System.out.println("1");
			out1.println("get sequence length");
String temp = in1.readLine();
System.out.println(temp);
System.out.println(Integer.parseInt(temp));
Integer vTemp = Integer.parseInt(temp);
			game.setSeqNum(vTemp);
			out2.println("set sequence length : " + game.getSeqNum());
			
			String seqBid = in2.readLine();
			seqBid = "1";
			System.out.println(seqBid);
			out1.println(seqBid);
			seqBid = in1.readLine();
			game.setGameValue( Double.valueOf(seqBid));
			System.out.println("pierwszy licytuje" +seqBid);
			out2.println(game.getGameValue());
			System.out.println("drugi licytuje" + seqBid);
			String currentBid;			
			while  ((currentBid = in2.readLine()) != null) 
				{ System.out.println(currentBid);
					if (game.getGameValue() == Double.valueOf(currentBid))
					{
						out1.println();
						game.setBidWiner(1);
					}
					else
					{	
					game.setGameValue( Double.valueOf(currentBid));
					game.setBidWiner(2);
					out1.println(game.getGameValue());
					};
					 
					if ((currentBid = in1.readLine()) != null)
						{
						if (game.getGameValue() == Double.valueOf(currentBid))
						{
							out2.println();
							game.setBidWiner(2);
						}
						else
						{	
						game.setGameValue( Double.valueOf(currentBid));
						out2.println(game.getGameValue());
						game.setBidWiner(1);
						};
					}
					else
					{
						out2.println();
					}
				};
				
				System.out.println( "final bid " + game.getGameValue());
				System.out.println( "winer " + game.getBidWiner() );
				out1.println( "winer " + game.getBidWiner() );
				out2.println( "winer " + game.getBidWiner() );
			// get seq from bidding winner
				
			// play game with bidding looser
			
		} catch (IOException e1) {
			// do nothing
		}
		
		try {
			socket1.close();
			socket1.close();
		} catch (IOException e) {
			// do nothing
		}
	}

	public void setGame(GameData game) {
		this.game = game;
	}

	public GameData getGame() {
		return game;
	}
}
